package com.wpc.servlet;

import java.io.IOException;
import java.util.List;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.wpc.action.SaveProductAction;
import com.wpc.form.ProductForm;
import com.wpc.model.Product;
import com.wpc.validate.ProductValidate;

@WebServlet(name = "ControllerServlet", urlPatterns = { "/product_list", "product_save", "product_input" })
public class ControllerServlet extends HttpServlet {

	private static final long serialVersionUID = 109809327L;

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

		process(req, resp);
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

		process(req, resp);
	}

	public void process(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		request.setCharacterEncoding("utf-8");
		response.setCharacterEncoding("utf-8");

		String uri = request.getRequestURI();
		int index = uri.indexOf("/");
		String action = uri.substring(index + 1);
		String despatchUrl = null;

		if (action.equals("product_input")) {

			despatchUrl = "/jsp/ProductForm.jsp";
		} else if (action.equals("product_save")) {

			ProductForm productForm = new ProductForm();
			productForm.setName(request.getParameter("name"));
			productForm.setDescription(request.getParameter("description"));
			productForm.setPrice(request.getParameter("price"));

			List<String> errors = ProductValidate.productValidate(productForm);

			if (errors.isEmpty()) {

				Product product = new Product();
				product.setName(productForm.getName());
				product.setDescription(productForm.getDescription());
				product.setPrice(Float.parseFloat(productForm.getPrice()));

				SaveProductAction saveProductAction = new SaveProductAction();
				saveProductAction.saveProduct(product);

				request.setAttribute("product", product);
				despatchUrl = "/jsp/ProductDetails.jsp";
			} else {
				request.setAttribute("errors", errors);
				request.setAttribute("product", productForm);
				despatchUrl = "/jsp/ProductForm.jsp";
			}
		} else if (action.equals("product_list") || action.isEmpty()) {

			despatchUrl = "/jsp/ProductList.jsp";
		}

		if (despatchUrl != null) {
			RequestDispatcher dispatcher = request.getRequestDispatcher(despatchUrl);
			dispatcher.forward(request, response);
		}
	}
}
